<?php

function __autoload($className) {
    $extensions = array(".php", ".class.php", ".inc");
    $paths = explode(PATH_SEPARATOR, get_include_path());
    foreach ($paths as $path) {
        $filename = $path . DIRECTORY_SEPARATOR . $className;
        foreach ($extensions as $ext) {
            if (is_readable($filename . $ext)) {
                require_once $filename . $ext;
                break;
           }
       }
    }
}

function set_error($error_code){
    if($error_code == 0){
        error_reporting(0);
    }else if($error_code == 1){
        error_reporting(E_ALL);
    }else if($error_code == 2){ 
        //Log and redirect page
        set_error_handler("error_handler");
    }
    
}

//handler and log an error
function error_handler($errno, $errstr, $errfile, $errline){
    $language = ($_GET["_LANGUAGE"] !== null && $_GET["_LANGUAGE"] != "" ? $_GET["_LANGUAGE"] : DEFAULT_LANGUAGE);
    $language_support = explode(",", DEFAULT_LANGUAGE_SUPPORT);
    if (!in_array($language, $language_support)) {
        $language = DEFAULT_LANGUAGE;
    }
    error_log("+ Date: " . date('d-m-Y h:i:s') . " +\n"
                    . "Code: $errno, File: $errfile, Line: $errline \n"
                    . $errstr . "\n\n"
                    , 3, ERROR_LOG_DIR);
    header("Location: " . APPLICATION_MESSAGE_URL . "/$language/exception");
}

function redirect($page){
    header("Location: " . $page);
}

function current_url()
{
    $pageURL = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
    $pageURL .= $_SERVER['SERVER_PORT'] != '80' ? $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"] : $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    return $pageURL;
}

function get_in_between_strings($start, $end, $s){
    $i = strpos($s,$start);
    $j = strpos($s,$end);
    return $i===false || $j===false ? false:substr(substr($s,$i,$j-$i),strlen($start));
}